<template>
  <div class="Role">
    <div class="top">
      <el-button type="primary" class="el-button" @click="add">新增</el-button>
    </div>
    <el-table
      :data="roles"
      height="100%"
      line-height="20px"
      border
      style="width: 100%"
    >
      <el-table-column prop="roleId" label="角色ID"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button size="mini" @click="handleUsers(scope.$index, scope.row)"
            >编辑用户</el-button
          >
          <el-button
            size="mini"
            @click="handlePermissions(scope.$index, scope.row)"
            >编辑权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑角色" :visible.sync="dialogFormRoleVisible">
      <el-form :model="roleForm">
        <el-form-item
          label="角色ID"
          v-show="false"
          :label-width="formLabelWidth"
        >
          <el-input v-model="roleForm.roleId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormRoleSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑角色用户" :visible.sync="dialogFormUserVisible">
      <el-form :model="userForm">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="userForm.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户" prop="user" :label-width="formLabelWidth">
          <!-- https://blog.csdn.net/weixin_44449838/article/details/113247836 -->
          <!-- 

          value-key="roleId"===> 如果绑定的是对象，则需要这个属性 el-option
         -->
          <el-select
            v-model="userForm.users"
            multiple
            collapse-tags
            style="margin-left: 20px"
            value-key="userId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="item.userName"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormUserSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog title="编辑角色权限" :visible.sync="dialogFormPermissionVisible">
      <el-form :model="permissionForm">
        <el-form-item
          label="角色ID"
          v-show="false"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="permissionForm.roleId"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input
            v-model="permissionForm.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限列表" :label-width="formLabelWidth">
          <el-checkbox-group class="checkbox-div" v-model="permissionIds">
            <div v-for="item in permissions" :key="item.permissionId">
              <el-checkbox
                :label="item.permissionId"
                :value="item.permissionId"
                >{{ item.name }}</el-checkbox
              >
              <el-checkbox
                v-for="child in item.children"
                :key="child.permissionId"
                :label="child.permissionId"
                :value="child.permissionId"
                >{{ child.name }}</el-checkbox
              >
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormPermissionVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="dialogFormPermissionSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { userList } from "../../apis/user";
import { permissionList } from "../../apis/permission";
import { Message } from "element-ui";
import {
  roleList,
  roleDelete,
  roleSave,
  roleUpdate,
  roleEditPermission,
  roleEditUser,
} from "../../apis/role";
// import { mapMutations } from "vuex";
export default {
  name: "Role",
  data() {
    return {
      form: {
        roleName: "",
      },
      userForm: {
        roleId: null,
        roleName: "",
        users: [],
      },
      roleForm: {
        roleId: null,
        roleName: "",
      },
      permissionForm: {
        roleId: null,
        roleName: "",
        permissions: [],
        // todo 放在这里，二级属性是数组的话，在vue2中无法做到响应式数据
        // permissionIds: [],
      },
      permissionIds: [],
      dialogFormRoleVisible: false,
      dialogFormVisible: false,
      dialogFormUserVisible: false,
      dialogFormPermissionVisible: false,
      formLabelWidth: "120px",
    };
  },
  methods: {
    add() {
      this.dialogFormVisible = true;
    },
    handleDelete(index, row) {
      roleDelete({ roleIds: [row.roleId] })
        .then(() => {
          roleList({})
            .then((data) => {
              let _this = this;
              _this.$store.commit("setRoles", data);
              Message({
                type: "success",
                duration: 3000,
                message: "删除成功",
              });
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch();
    },
    handleUsers(index, row) {
      this.userForm = row;
      userList({})
        .then((data) => {
          let _this = this;
          _this.$store.commit("setUsers", data);
        })
        .catch(function (error) {
          console.log(error);
        });
      this.dialogFormUserVisible = true;
    },
    handlePermissions(index, row) {
      this.permissionForm = row;
      if (this.permissionForm.permissions == null) {
        this.permissionIds = [];
      } else {
        this.permissionIds = row.permissions.map((v) => {
          return v.permissionId;
        });
      }
      permissionList({})
        .then((data) => {
          let _this = this;
          console.log(data);
          _this.$store.commit("setPermissions", data);
        })
        .catch(function (error) {
          console.log(error);
        });
      this.dialogFormPermissionVisible = true;
    },
    handleEdit(index, row) {
      this.roleForm = row;
      this.dialogFormRoleVisible = true;
    },
    dialogFormSubmit() {
      roleSave(this.form)
        .then(() => {
          roleList({})
            .then((data) => {
              let _this = this;
              _this.$store.commit("setRoles", data);
              Message({
                type: "success",
                duration: 3000,
                message: "新增成功",
              });
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch();

      this.dialogFormVisible = false;
    },
    dialogFormRoleSubmit() {
      roleUpdate(this.roleForm)
        .then(() => {
          roleList({})
            .then((data) => {
              let _this = this;
              _this.$store.commit("setRoles", data);
              Message({
                type: "success",
                duration: 3000,
                message: "更新成功",
              });
            })
            .catch(function (error) {
              console.log(error);
            });
        })
        .catch();

      this.dialogFormRoleVisible = false;
    },
    dialogFormUserSubmit() {
      roleEditUser(this.userForm)
        .then(() => {
          Message({
            type: "success",
            duration: 3000,
            message: "更新成功",
          });
        })
        .catch();

      this.dialogFormUserVisible = false;
    },
    dialogFormPermissionSubmit() {
      let ps = [];
      this.permissions.forEach((e) => {
        ps.push(e);
        if (e.children != null) {
          ps.push(...e.children);
        }
      });
      if (this.permissionIds != null) {
        this.permissionForm.permissions = ps.filter((item) => {
          return this.permissionIds.includes(item.permissionId);
        });
      }
      roleEditPermission(this.permissionForm)
        .then(() => {
          Message({
            type: "success",
            duration: 3000,
            message: "更新成功",
          });
        })
        .catch();

      this.dialogFormPermissionVisible = false;
    },
  },
  computed: {
    ...mapState(["roles", "users", "permissions"]),
  },
  created() {
    roleList({})
      .then((data) => {
        let _this = this;
        _this.$store.commit("setRoles", data);
      })
      .catch(function (error) {
        console.log(error);
      });
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.Role {
  height: 100%;
}
.top {
  text-align: right;
}
.el-button {
  margin-bottom: 10px;
}
.checkbox-div div {
  text-align: left;
}
</style>
